package com.tt1000.settlementplatform.utils;

import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.tt1000.settlementplatform.MainActivity;
import com.tt1000.settlementplatform.app.MyApplication;
import com.tt1000.settlementplatform.bean.member.MemberTypeRecord;
import com.tt1000.settlementplatform.bean.member.MemberTypeRecordDao;
import com.tt1000.settlementplatform.bean.member.TfDiscountRecord;
import com.tt1000.settlementplatform.bean.member.TfDiscountRecordDao;
import com.tt1000.settlementplatform.bean.member.TfMealTimes;
import com.tt1000.settlementplatform.bean.member.TfMealTimesDao;
import com.tt1000.settlementplatform.feature.network.ApiService;
import com.tt1000.settlementplatform.feature.network.LocalRetrofit;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.tt1000.settlementplatform.utils.MyConstant.TAG;

public class MyUtil {

    private static final String[] sSyncTableColumns = new String[]{"SEQNO", "TABLENAME", "PRIMARYKEY","QUESTTIME", "ISM_STATUS", "INIT_STATUS",
            "CLIENT_CODE", "STORE_CODE", "CREATETIME","UPDATETIME", "ANOTHER_NAME"};

    public static SQLiteDatabase readDatabase(String dbPath, String dbName) {
        File path = new File(dbPath);
        File dbFile = new File(dbPath + dbName);
        SQLiteDatabase sqLiteDatabase = null;
        InputStream input;
        FileOutputStream output;
        try {

            if (!path.exists()) {
                path.mkdirs();
            }

            if (!dbFile.exists()) {
//                dbFile.mkdirs();
                // 不存在，则加载assets中的db文件到本地
                AssetManager am = MyApplication.getContext().getAssets();
                input = am.open("local_db.db");
                output = new FileOutputStream(dbFile);
                byte[] buffer = new byte[8192];
                int count = 0;
                while ((count = input.read(buffer)) != -1) {
                    output.write(buffer, 0, count);
                }
                output.flush();
                output.close();
                input.close();
            }

            sqLiteDatabase = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE);


        } catch (IOException e) {
            e.printStackTrace();
        }

        return sqLiteDatabase;
    }

    /**
     * 同步表
     * SEQNO	主键
     * TABLENAME	表名
     * PRIMARYKEY	表主键
     * QUESTTIME	间隔时间
     * ISM_STATUS	同步状态
     * INIT_STATUS	初始状态
     * CLIENT_CODE	客户代码
     * STORE_CODE	店铺代码
     * CREATETIME	创建时间
     * UPDATETIME	更新时间
     * ANOTHER_NAME	表名
     */
    public static void createOrUpdateSyncTable(String syncTableName, List<String> newData) {

        SQLiteDatabase database = readDatabase(MyConstant.DB_PATH, MyConstant.DB_NAME);
        ContentValues values = new ContentValues();

        Cursor cursor = database.query(MyConstant.SYNC_TABLE_RECORD, null, "TABLENAME=?", new String[]{syncTableName}, null, null, null);
        // 创建记录
        if (cursor.getCount() == 0) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss");
            values.put("SEQNO", "123123");
            values.put("TABLENAME", syncTableName);
            values.put("PRIMARYKEY", "123123");
            values.put("QUESTTIME", "123123");
            values.put("ISM_STATUS", "");
            values.put("INIT_STATUS", "");
            values.put("CLIENT_CODE", "");
            values.put("STORE_CODE", "");
            values.put("CREATETIME", format.format(new Date()));
            values.put("ANOTHER_NAME", "123123");
            database.insert(MyConstant.SYNC_TABLE_RECORD, null, values);
            return;
        }
        ContentValues updateValues = new ContentValues();
        // 更新数据
        for (int i = 0; i < newData.size(); i++) {
            if (sSyncTableColumns[i].equals("CREATETIME")) {
                // 更新数据的数据中不包含创建时间
                // 同时也不允许用户设置这个数据
                continue;
            }
            updateValues.put(sSyncTableColumns[i], newData.get(i));
        }
//        database.update(MyConstant.SYNC_TABLE_RECORD, updateValues, "TABLENAME=?", new String[]{syncTableName});
    }

    public static String encryptMD5(String inStr){
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char)(a[i] ^ 0x74);
        }
        String s = new String(a);
        return s;
    }

    public static String getPrimaryValue() {
        try {
                JSONObject random=new JSONObject();
                random.put("length", 1000);
                JSONObject randomJson=new JSONObject();
                randomJson.put("length", 100);
                return System.currentTimeMillis()
                        +String.valueOf((int)(Math.random()*randomJson.getInt("length")
                        +randomJson.getInt("length")))
                        +String.valueOf((int)(Math.random()*random.getInt("length")
                        +random.getInt("length")));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getCurMealTimes() {
        String curDate = MyUtil.obtainCurrentSysDate(1);
        TfMealTimes mealTimes = MyApplication.getInstance().queryBuilder(TfMealTimes.class)
                .where(TfMealTimesDao.Properties.STARTTIME.le(curDate),
                        TfMealTimesDao.Properties.ENDTIME.ge(curDate))
                .build()
                .unique();
        if (mealTimes != null) {
            return mealTimes.getMT_ID();
        }
        return "";
    }

    public static String dateConversion(long millis) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date(millis));
    }

    /**
     * 隐藏烦人的输入法
     * @param context
     * @param editText
     */
    public static void hideInputMethodManager(Context context, EditText editText) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    /**
     *
     * @param type 0:yyyy-MM-dd 1: HH:mm:ss 2 yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String obtainCurrentSysDate(int type) {
        SimpleDateFormat format = new SimpleDateFormat();
        switch (type) {
            case 0:
                format.applyPattern("yyyy-MM-dd");
                break;
            case 1:
                format.applyPattern("HH:mm:ss");
                break;
            case 2:
                format.applyPattern("yyyy-MM-dd HH:mm:ss");
        }
        Date date = new Date();
        return format.format(date);
    }

    public static boolean networkState = false;
    /**
     * 网络连通性
     * @param context
     * @return
     */

    public static boolean obtainNetworkStatus(Context context) {
        if(null == context){
            networkState = false;
            return false;
        }
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(null == networkInfo){
            networkState = false;
            return false;
        }else{
            if(networkInfo.isAvailable()){
                networkState = true;
                return  true;
            }else{
                if (MainActivity.gUiHandler != null) {
                    MainActivity.gUiHandler.obtainMessage(MainActivity.WIFI_ERROR).sendToTarget();
                }
                networkState = false;
                return false;
            }
        }
    }


//    public static boolean obtainNetworkStatus(Context context) {
//        try {
//            LocalRetrofit.createService().obtainHeart()
//                    .subscribeOn(Schedulers.io())
//                    .subscribe(new Observer<Object>() {
//                        @Override
//                        public void onCompleted() {
//                            Log.d("network", "onCompleted: ");
//                            networkState = true;
//                        }
//
//                        @Override
//                        public void onError(Throwable e) {
//                            Log.d("network", "onError: " + e.getMessage());
//                            networkState = false;
//                        }
//
//                        @Override
//                        public void onNext(Object o) {
//                            Log.d("network", "onNext: ");
//                            networkState = true;
//                        }
//                    });
//            return networkState;
//        } catch (Exception e) {
//            e.printStackTrace();
//            if (MainActivity.gUiHandler != null) {
//                MainActivity.gUiHandler.obtainMessage(MainActivity.WIFI_ERROR).sendToTarget();
//            }
//            return false;
//        }
//
//    }

    public static String strToHexString(String toConvert) {
        String result = "";
        for (int i = 0; i < toConvert.length(); i++) {
            int c = toConvert.charAt(i);
            result += Integer.toHexString(c);
        }
        return result;
    }

    public static final byte[] hex2byte(String hex) throws IllegalArgumentException {
        if (hex.length() % 2 != 0) {
            throw new IllegalArgumentException();
        }
        char[] arr = hex.toCharArray();
        byte[] b = new byte[hex.length() / 2];
        for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
            String swap = "" + arr[i++] + arr[i];
            int byteint = Integer.parseInt(swap, 16) & 0xFF;
            b[j] = new Integer(byteint).byteValue();
        }
        return b;
    }

    public static String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
        String out = "";

        for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }

    public static String getMacAddress() {
        StringBuilder result = new StringBuilder(callCmd());
        String Mac = "";

        //对该行数据进行解析
        //例如：eth0      Link encap:Ethernet  HWaddr 00:16:E8:3E:DF:67
        if (result.length() > 0 && result.toString().contains("HWaddr")) {
            Mac = result.substring(result.indexOf("HWaddr") + 6, result.length() - 1);
//            Log.i("test", "Mac:" + Mac + " Mac.length: " + Mac.length());

            if (Mac.length() > 1) {
                Mac = Mac.replaceAll(" ", "");
                result = new StringBuilder();
                String[] tmp = Mac.split(":");
                for (String aTmp : tmp) {
                    result.append(aTmp);
                }
                return result.toString();
            }
//            Log.i("test", result + " result.length: " + result.length());
        }
        return result.toString();
    }

    public static String callCmd() {
        String result = "";
        String line = "";
        try {
            Process proc = Runtime.getRuntime().exec("busybox ifconfig");
            InputStreamReader is = new InputStreamReader(proc.getInputStream());
            BufferedReader br = new BufferedReader(is);

            //执行命令cmd，只取结果中含有filter的这一行
            while ((line = br.readLine()) != null && !line.contains("HWaddr")) {
                //result += line;
            }
            is.close();
            result = line;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 判断服务器地址是否可用
     * @return
     */
    public static boolean isConfigServer() {
        try {
            LocalRetrofit.getInstance().create(ApiService.class);
            return true;
        } catch (Exception e) {
            if (MainActivity.gUiHandler != null) {
                MainActivity.gUiHandler.obtainMessage(MainActivity.WIFI_ERROR).sendToTarget();
            }
            e.printStackTrace();
            return false;
        }
    }
    public static boolean isEmpty(String temp){
        if(null == temp || temp.equals("") || temp.length() <=0){
            return true;
        }
        return false;
    }
    public static boolean isNotEmpty(String temp){
        return !isEmpty(temp);
    }

    public static boolean isNumber(String str) {
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
        java.util.regex.Matcher match = pattern.matcher(str);
        if (str.contains(".") && str.length() - 1 == str.indexOf(".")) {
            return false;
        }
        if (!match.matches() || str.equals("0")||str.equals("0.0")||str.equals("0.00")|| TextUtils.isEmpty(str)) {
            return false;
        } else {
            return true;
        }
    }
    /**
     * 根据icid计算得出会员卡号
     *
     * @param smartCardId
     * @return
     */
    public static long computeMemberId(String smartCardId) {
        byte[] arr_test = MyUtil.hex2byte(smartCardId);
        long convertId = 0;
        if (arr_test.length == 4) {
            long shu_0 = arr_test[0] & 0xFF;
            long shu_1 = arr_test[1] & 0xFF;
            long shu_2 = arr_test[2] & 0xFF;
            long shu_3 = arr_test[3] & 0xFF;
            long i_test = shu_0 + shu_1 * 256L + shu_2 * 256L * 256L + shu_3 * 256L * 256L * 256L;
            convertId = i_test;
        }
        return convertId;
    }
    /**
     * 会员折扣
     * @param mi_type
     * @return
     */
    public static int getDisCountForMember(String mi_type) {
        int disCount = 100;
        if(mi_type!=null)
        {
            List<TfDiscountRecord> discountRecordList = MyApplication.getInstance().queryBuilder(TfDiscountRecord.class)
                    .where(TfDiscountRecordDao.Properties.DISCOUNT_STATUS.eq(1),
                            TfDiscountRecordDao.Properties.DISCOUNT_TYPE.eq(1))
                    .build()
                    .list();
            if(discountRecordList!=null && discountRecordList.size()>0) {
                TfDiscountRecord tfDiscountRecord = discountRecordList.get(0);
                if(tfDiscountRecord!=null)
                {
                    List<MemberTypeRecord> memberTypeRecordList = MyApplication.getInstance().queryBuilder(MemberTypeRecord.class)
                            .where(MemberTypeRecordDao.Properties.SEQNO.eq(mi_type))
                            .build()
                            .list();
                    if(memberTypeRecordList!=null && memberTypeRecordList.size()>0)
                    {
                        MemberTypeRecord memberTypeRecord = memberTypeRecordList.get(0);
                        if(memberTypeRecord!=null)
                        {
                            try {
                                disCount = Integer.parseInt(memberTypeRecord.getDISCOUNT_RATE());
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        return disCount;
    }
    /**
     * 获得全员折扣
     * @return
     */
    public static int getDisCountForAll() {
        int disCount = 100;
        List<TfDiscountRecord> discountRecordList = MyApplication.getInstance().queryBuilder(TfDiscountRecord.class)
                .where(TfDiscountRecordDao.Properties.DISCOUNT_STATUS.eq(1),
                        TfDiscountRecordDao.Properties.DISCOUNT_TYPE.eq(0))
                .build()
                .list();
        if(discountRecordList!=null && discountRecordList.size()>0) {
            TfDiscountRecord tfDiscountRecord = discountRecordList.get(0);
            if (tfDiscountRecord != null) {
                try {
                    disCount = Integer.parseInt(tfDiscountRecord.getDISCOUNT_RATE_C1());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        Log.i(TAG, "getDisCountForAll: "+disCount);
        return disCount;
    }

    /**
     * 返回折扣率
     * DISCOUNT_STATUS: 0 关闭 1开启
     *
     * @param discountType 0 全民折扣 1 会员折扣 2 自定义折扣
     * @return
     */
    private float getDiscountRate(int discountType) {
        float rate = 1;
        List<TfDiscountRecord> discountRecordList = MyApplication.getInstance().queryBuilder(TfDiscountRecord.class)
                .where(TfDiscountRecordDao.Properties.DISCOUNT_STATUS.eq(1),
                        TfDiscountRecordDao.Properties.DISCOUNT_TYPE.eq(discountType))
                .build()
                .list();
        if (discountRecordList == null || discountRecordList.isEmpty()) {
            return rate;
        }
        TfDiscountRecord discountRecord = discountRecordList.get(0);
        if (discountRecord != null) {
            rate = Float.parseFloat(discountRecord.getDISCOUNT_RATE_C1()) / 100f;
            return rate;
        }
        return rate;
    }
    public static long stringToLong(String strTime, String formatType)
            throws ParseException {
        Date date = stringToDate(strTime, formatType); // String类型转成date类型
        if (date == null) {
            return 0;
        } else {
            long currentTime = dateToLong(date); // date类型转成long类型
            return currentTime;
        }
    }
    public static Date stringToDate(String strTime, String formatType)
            throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        date = formatter.parse(strTime);
        return date;
    }
    public static long dateToLong(Date date) {
        return date.getTime();
    }
}
